package demo1;

import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * @Author liangzai
 * @Description:
 */
public class Training {
    //两球之间的磁力
    private boolean check(int[] position, int m, int dis) {
        int lastPos = position[0];
        int rest = m - 1;
        for (int i = 1; i < position.length; i++) {
            int pos = position[i];
            if (pos - lastPos >= dis) {
                lastPos = pos;
                rest -= 1;
                if (rest == 0) break;
            }
        }
        return rest == 0;
    }

    public int maxDistance(int[] position, int m) {
        Arrays.sort(position);
        int left = 1, right = position[position.length - 1] - position[0];
        int dis = 1;

        // 在[left, right]中寻找解
        while (left < right) {
            dis = left + (right - left + 1) / 2;
            if (check(position, m, dis)) {
                left = dis;
            } else {
                right = dis - 1;
            }
        }

        return left;
    }
}
